
import { useEffect, useState, useRef } from 'react';
import _ from 'lodash';
import BizBody from '@inbiz/basic/BizBody';
import BizHeader from '@inbiz/basic/BizHeader';
import BizTitle from '@inbiz/basic/BizTitle';
import { getEditor, initSocket } from '@inbiz/utils';
import Small from './Small';
import List from './List';
import Grid from './Grid';
import MessagePortal from './MessagePortal';
import MessageDetailPortal from './MessageDetailPortal';
import { useGetGroups } from './customHooks';

export default function Message(props: any) {
    const { controlId, h5Viewtype, msgGroupLayout, range, msgGroup, title, titleIcon, iconGrid, listGroup, emit, callBackEvents } = props;
    const [loading, groupData, setGroupData, getGroups] = useGetGroups({ h5Viewtype, msgGroupLayout, range, msgGroup, iconGrid, listGroup });
    const [messagePortalVisiable, setMessagePortalVisiable] = useState(false);
    const [messageDetailVisiable, setMessageDetailVisiable] = useState(false);
    const [currentGroup, setCurrentGroup] = useState(null);
    const [currentMessage, setCurrentMessage] = useState(null);
    const isEditor = getEditor();
    const portalRef = useRef<any>();

    const onClickItem = (item: any) => {
        let _href = window.location.href;
        if(_href?.indexOf('portalType=list') == -1){
            _href = _href + '?portalType=list';
            window.history.pushState({}, '', `${_href}`);
            setCurrentGroup(item);
            localStorage.setItem(`${controlId}-message-h5-current-group`, JSON.stringify(item));
        }
    }

    useEffect(() => {
        const fn = (e: any) => {
            if (e?.data?.type === 'message') {
                const { wapMessage, returnUrl, key, appId, time } = e?.data?.data || {};
                let _groupData = [...groupData];
                if (_.isArray(groupData?.[0])) {
                    for (let i = 0; i < _groupData.length; i++) {
                        let curGroupData = [..._groupData[i]]
                        for (let j = 0; j < curGroupData.length; j++) {
                            if (curGroupData[j]?.AppId == appId && curGroupData[j]?.GroupKey == key) {
                                curGroupData[j].Count = curGroupData[j]?.Count + 1;
                                curGroupData[j].AllCount = curGroupData[j]?.AllCount + 1;
                                curGroupData[j].MsgTime = time;
                                curGroupData[j].WapMsgTitle = wapMessage;
                            }
                        }
                        _groupData[i] = curGroupData;
                    }
                } else {
                    _groupData = _groupData?.map((item) => {
                        if (item?.AppId == appId && item?.GroupKey == key) {
                            return {
                                ...item,
                                Count: item?.Count + 1,
                                AllCount: item?.AllCount + 1,
                                MsgTime: time,
                                WapMsgTitle: wapMessage,
                            }
                        } else {
                            return item;
                        }
                    });
                }
                setGroupData(_groupData);
                if (messagePortalVisiable) {
                    portalRef?.current?.getGroupMessages()
                }
            }
        };
        if (!isEditor) window.addEventListener('message', fn, false);
        // @ts-ignore
        if (!window.socket && !isEditor) {
            // @ts-ignore
            window.socket = true
            // @ts-ignore
            window.socket = initSocket()
        }
        return () => {
            if (!isEditor) window.removeEventListener('message', fn);
        };
    }, [groupData, messagePortalVisiable, portalRef]);

    useEffect(() => {
        if (window.location.href?.indexOf('portalType=detail') != -1) {
            setMessageDetailVisiable(true);
            setMessagePortalVisiable(false)
        } else if (window.location.href?.indexOf('portalType=list') != -1) {
            setMessageDetailVisiable(false);
            setMessagePortalVisiable(true);
        } else {
            setMessageDetailVisiable(false);
            setMessagePortalVisiable(false);
        }
    }, [window.location.href])

    if (h5Viewtype == 'small') {
        return (
            <Small {...props} groupData={groupData} />
        )
    }

    if (h5Viewtype == 'list') {
        let _component = null;
        switch (msgGroupLayout) {
            case 'list':
                _component = <List data={_.isArray(groupData?.[0]) ? [] : groupData} onClickItem={onClickItem} />;
                break;
            case 'grid':
                _component = <Grid data={_.isArray(groupData?.[0]) ? [] : groupData} onClickItem={onClickItem} />;
                break;
            case 'listAndGrid':
                _component = (
                    <>
                        <Grid data={_.isArray(groupData?.[0]) ? groupData?.[0] : []} onClickItem={onClickItem} />
                        <List data={_.isArray(groupData?.[1]) ? groupData?.[1] : []} onClickItem={onClickItem} />
                    </>
                )
                break;
            default:
                _component = null
        };
        return (
            <>
                <BizHeader {...props}>
                    <BizTitle titleOption={title} iconOption={titleIcon} />
                </BizHeader>
                <BizBody {...props}>
                    {_component}
                    {
                        messagePortalVisiable
                        &&
                        <MessagePortal
                            ref={portalRef}
                            group={currentGroup}
                            emit={emit}
                            callBackEvents={callBackEvents}
                            getGroups={getGroups}
                            setCurrentMessage={setCurrentMessage}
                            controlId={controlId}
                        />
                    }
                    {
                        messageDetailVisiable
                        &&
                        <MessageDetailPortal
                            message={currentMessage}
                            emit={emit}
                            callBackEvents={callBackEvents}
                            controlId={controlId}
                        />
                    }
                </BizBody>
            </>
        )
    }
};